<?php

	session_start();
	
	class JWBugz
	{
	
		public static $apiURL = 'https://csnmedia.fogbugz.com/api.asp?'; 
		public static $loginString = 'cmd=logon&email=jeff@csnmedia.com&password=csng4545';
		public static $listFiltersString = 'cmd=listFilters';
		public static $setCurrentFilter = 'cmd=setCurrentFilter';
		public static $searchCmd = "cmd=search";
		
		/* SESSION VARS
		
		token
		
		*/
		
		public static function getData($args)
		{
			$url = self::$apiURL . $args . "&token=" . self::getToken();
			return simplexml_load_file($url);
		}
	
		public static function resetToken()
		{
			return self::getData(self::$loginString);
		}
		
		public function setToken()
		{
			$_SESSION['fbToken'] = (string)self::resetToken()->token;
			return self::getToken();
		}
		
		public function getToken()
		{
			return $_SESSION['fbToken'];
		}
		
		public function getFilters()
		{
			$xml = self::getData(self::$listFiltersString);
			self::printFilters($xml);
		}
		
		public function printFilters($xml)
		{
			echo "<h1>Filters</h1>";
			
			echo "<ul>";

			foreach($xml->children() as $child)
			{
				foreach($child->children() as $child2)
				{
					foreach($child2[0]->attributes() as $a => $b) {
						/*
						if ($a == 'type')
						{
							if ($b != 'builtin')
								continue 2;
						}
						*/
						if ($a=='sFilter')
							$sFilter = $b;
					}
						echo "<li><a href='" . self::$apiURL . self::$setCurrentFilter . "&sFilter=" . $sFilter . "'>" . $child2 . "</li>";
				}
			}
			
			echo "</ul>";
		}
		
		public function setCurrentFilter($filter)
		{
			$xml = self::getData(self::$setCurrentFilter . "&sFilter=" . $filter);
		}
		
		public function fbSearch($q = null, $cols = null)
		{
			$xml = self::getData(self::$searchCmd . "&q=" . $q . "&cols=" . $cols);
			self::printCases($xml);
		}
		
		public function printCases($xml)
		{
			echo "Showing: " . $xml->description . "<br /><br />";
		
			echo "<table>";
		
			foreach($xml->children() as $child)
			{
				foreach($child->children() as $child2)
				{
					foreach($child2[0]->attributes() as $a => $b) {
						if ($a=='ixBug')
							$ix = $b;
					}
						echo "<tr><td>" . $child2->sTitle . "</td><td>" . $ix . "</td></tr>";
				}
			}
			
			echo "</table>";
		}
			
	}

	$app = new JWBugz();

	$app->setToken();

	echo "\n\n";
	
	//$app->getFilters();
	
	$app->setCurrentFilter(79);
	
	$app->fbSearch(null,"sTitle");
	

?>